<?php
/**
 * 递归转义数组
 *
 * @param array $arr
 */
function adds(array &$arr)
{
	foreach ($arr as $key=>$value)
	{
		if (is_array($value))
		{
			adds($arr);
		}
		else 
		{
			$arr[$key] = addslashes($value);
		}
	}
}

/**
 * 给数据库字段添加`,防止字段名冲突
 *
 * @param mixed $field
 * @return string
 */
function escapeField($field)
{
	if (is_array($field))
	{
		$str = null;
		foreach ($field as &$value)
		{
			$str .= '`'.$value.'`, ';
		}
		$str = mb_strcut($str, 0, mb_strlen($str) - 2);
		
		return $str;
	}
	else 
	{
		return '`'.$field.'`';
	}
}

function escapeTable($tableName)
{
	return escapeField($tableName);
}

/**
 * 给插入数据库的值加上''
 *
 * @param mixed $value
 * @return string
 */
function escapeValue($value)
{
	if (is_array($value))
	{
		$str = null;
		foreach ($value as &$v)
		{
			if ($v != 'NULL')
			{
				$str .= '\''.addslashes($v).'\', ';
			}
			else 
			{
				$str .= $v.', ';
			}
		}
		$str = mb_strcut($str, 0, mb_strlen($str) - 2);
		return $str;
	}
	else 
	{
		return '`'.$value.'`';
	}
}

/**
 * 异常处理函数
 *
 * @param Exception $exception
 */
function ExceptionHandle(Exception $exception)
{
	$exceptionClassName = get_class($exception);
	$exceptionInfo = $exception->getMessage();
	$file = $exception->getFile();
	$line = $exception->getLine();
	$trace = $exception->getTrace();
	$traceInfo = array();
	foreach ($trace as $key=>$value)
	{
		$args = null;
		$size = count($value['args']);
		if ($size > 0)
		{
			for($i=0; $i<$size-1; $i++)
			{
				$args .= $value['args'][$i].', ';
			}
			$args .= $value['args'][$size-1];
		}
		$class = (!empty($value['class'])) ? $value['class'] : null;
		$type = (!empty($value['type'])) ? $value['type'] : null;
		array_push($traceInfo, "#$key: {$value['file']}({$value['line']}): {$class}{$type}{$value['function']}($args)");
	}
	$lastStackNo = count($trace);
	array_push($traceInfo, "#$lastStackNo {main}");
	
	include_once('Tpl/exceptionHandle.php');
}